<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>EmailCraft - 专业邮件设计工具</title>
    <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@400;500;600&display=swap" rel="stylesheet">
    <link rel="icon" type="image/ico" href="/pc/inbox_icon.png">
    <style>
        /* 样式保持不变 */
        :root {
            --primary-color: #4f46e5;
            --secondary-color: #818cf8;
            --background-color: #f3f4f6;
            --text-color: #1f2937;
            --light-text-color: #6b7280;
            --border-color: #e5e7eb;
        }

        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Poppins', sans-serif;
            background-color: var(--background-color);
            color: var(--text-color);
            line-height: 1.6;
        }

        .navbar {
            background-color: #ffffff;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            z-index: 1000;
        }

        .navbar-content {
            max-width: 1200px;
            margin: 0 auto;
            display: flex;
            justify-content: space-between;
            align-items: center;
            padding: 1rem 2rem;
        }

        .logo {
            font-size: 1.5rem;
            font-weight: 600;
            color: var(--primary-color);
            text-decoration: none;
        }

        .main-content {
            max-width: 1200px;
            margin: 6rem auto 2rem;
            padding: 0 2rem;
        }

        .editor-container {
            background-color: #ffffff;
            border-radius: 0.5rem;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.05);
            overflow: hidden;
        }

        #editor {
            width: 100%;
            height: calc(100vh - 13rem);
            border: none;
        }

        .button-container {
            padding: 1rem;
            background-color: #ffffff;
            display: flex;
            justify-content: space-between;
            align-items: center;
            gap: 1rem;
            border-top: 1px solid var(--border-color);
        }

        .button {
            display: inline-flex;
            align-items: center;
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
        }

        .button svg {
            width: 1.25rem;
            height: 1.25rem;
            margin-right: 0.5rem;
        }

        .button-primary {
            background-color: var(--primary-color);
            color: #ffffff;
            border: none;
        }

        .button-primary:hover {
            background-color: var(--secondary-color);
        }

        .button-secondary {
            background-color: #ffffff;
            color: var(--text-color);
            border: 1px solid var(--border-color);
        }

        .button-secondary:hover {
            background-color: #f9fafb;
        }

        #preview-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease-out;
        }

        @keyframes fadeIn {
            from { opacity: 0; }
            to { opacity: 1; }
        }

        .modal-content {
            background-color: #ffffff;
            margin: 5% auto;
            padding: 2rem;
            border-radius: 0.5rem;
            width: 80%;
            max-width: 800px;
            max-height: 80%;
            overflow-y: auto;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            animation: slideIn 0.3s ease-out;
        }

        @keyframes slideIn {
            from { transform: translateY(-50px); opacity: 0; }
            to { transform: translateY(0); opacity: 1; }
        }

        .close {
            color: var(--light-text-color);
            float: right;
            font-size: 28px;
            font-weight: bold;
            cursor: pointer;
            transition: color 0.2s ease-in-out;
        }

        .close:hover {
            color: var(--text-color);
        }

        .toast {
            position: fixed;
            top: 50%; /* 垂直居中 */
            left: 50%; /* 水平居中 */
            transform: translate(-50%, -50%); /* 确保完全居中 */
            background-color: var(--primary-color);
            color: #ffffff;
            padding: 1rem 2rem;
            border-radius: 0.25rem;
            box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
            display: none;
            animation: slideUp 0.3s ease-out;
            z-index: 1001; /* 确保 toast 在其他内容之上 */
        }

        @keyframes fadeInOut {
            0% { opacity: 0; }
            10% { opacity: 1; }
            90% { opacity: 1; }
            100% { opacity: 0; }
        }

        .toast {
            animation: fadeInOut 3s ease-out; /* 3秒后自动消失 */
        }

        .type-selector {
            display: flex;
            align-items: center;
            gap: 1rem;
        }

        .type-selector label {
            font-weight: 500;
        }

        .type-selector select {
            padding: 0.5rem;
            border-radius: 0.25rem;
            border: 1px solid var(--border-color);
            background-color: #ffffff;
            font-size: 1rem;
            color: var(--text-color);
        }

        .export-options {
            display: flex;
            gap: 1rem;
        }

        /* 新增弹窗样式 */
        #title-modal {
            display: none;
            position: fixed;
            z-index: 1000;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(0, 0, 0, 0.5);
            animation: fadeIn 0.3s ease-out;
        }

        .title-modal-content {
            background-color: #ffffff;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            padding: 2rem;
            border-radius: 0.5rem;
            width: 50%;
            max-width: 500px;
            box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
            animation: slideIn 0.3s ease-out;
        }

        .title-modal-content h2 {
            margin-bottom: 1rem;
            font-size: 1.5rem;
            font-weight: 600;
        }

        .title-modal-content input {
            width: 100%;
            padding: 0.5rem;
            border-radius: 0.25rem;
            border: 1px solid var(--border-color);
            font-size: 1rem;
            margin-bottom: 1rem;
        }

        .title-modal-content button {
            padding: 0.5rem 1rem;
            border-radius: 0.25rem;
            font-size: 1rem;
            font-weight: 500;
            cursor: pointer;
            transition: all 0.2s ease-in-out;
        }

        .title-modal-content button.button-primary {
            background-color: var(--primary-color);
            color: #ffffff;
            border: none;
        }

        .title-modal-content button.button-primary:hover {
            background-color: var(--secondary-color);
        }

        .title-modal-content button.button-secondary {
            background-color: #ffffff;
            color: var(--text-color);
            border: 1px solid var(--border-color);
        }

        .title-modal-content button.button-secondary:hover {
            background-color: #f9fafb;
        }

        /* 发送邮件弹窗样式 */
        #send-modal {
            display: none;
            position: fixed;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            background: rgba(0, 0, 0, 0.5);
            backdrop-filter: blur(5px);
            z-index: 2000;
        }

        .send-modal-content {
            background: rgba(255, 255, 255, 0.9);
            border-radius: 12px;
            padding: 2rem;
            width: 90%;
            max-width: 500px;
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
            border: 1px solid rgba(255, 255, 255, 0.2);
        }

        .form-group {
            margin-bottom: 1.5rem;
        }

        .form-group label {
            display: block;
            margin-bottom: 0.5rem;
            font-weight: 500;
            color: var(--text-color);
        }

        .form-group input {
            width: 100%;
            padding: 0.75rem;
            border: 1px solid var(--border-color);
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.8);
            transition: all 0.3s ease;
        }

        .form-group input:focus {
            outline: none;
            border-color: var(--primary-color);
            box-shadow: 0 0 0 3px rgba(79, 70, 229, 0.1);
        }

        .form-buttons {
            display: flex;
            gap: 1rem;
            margin-top: 1.5rem;
        }
        /* 加载动画 */
        .spinner {
            display: inline-block;
            width: 1rem;
            height: 1rem;
            border: 2px solid rgba(255,255,255,0.3);
            border-radius: 50%;
            border-top-color: #fff;
            animation: spin 1s ease-in-out infinite;
        }

        @keyframes spin {
            to { transform: rotate(360deg); }
        }

        /* 附件上传提示 */
        .hint {
            display: block;
            margin-top: 0.25rem;
            font-size: 0.875rem;
            color: var(--light-text-color);
        }

        /* 文件输入美化 */
        input[type="file"] {
            width: 100%;
            padding: 0.5rem;
            border: 1px solid var(--border-color);
            border-radius: 0.5rem;
            background: rgba(255,255,255,0.9);
        }
        /* 文件上传容器 */
        .file-upload {
            position: relative;
            width: 100%;
        }

        /* 隐藏原生input */
        .file-upload input[type="file"] {
            position: absolute;
            width: 100%;
            height: 100%;
            opacity: 0;
            cursor: pointer;
            z-index: 2;
        }

        /* 自定义按钮样式 */
        .custom-file-input {
            display: flex;
            align-items: center;
            gap: 0.75rem;
            padding: 0.75rem 1.25rem;
            background: rgba(255,255,255,0.9);
            border: 2px dashed var(--border-color);
            border-radius: 8px;
            transition: all 0.3s ease;
        }

        .custom-file-input:hover {
            background: rgba(79, 70, 229, 0.05);
            border-color: var(--primary-color);
        }

        .custom-file-input svg {
            width: 1.5rem;
            height: 1.5rem;
            color: var(--primary-color);
        }

        .custom-file-input span {
            color: var(--text-color);
            font-weight: 500;
        }

        /* 优化文件信息显示样式 */
        .file-info {
            white-space: pre-wrap;
            background: #f8f9fa;
            border-radius: 4px;
            padding: 8px;
            margin-top: 8px;
            border: 1px dashed #dee2e6;
            max-height: 200px;
            overflow-y: auto;
            line-height: 1.5;
        }

        /* 拖拽状态 */
        .file-upload.dragover .custom-file-input {
            background: rgba(79, 70, 229, 0.1);
            border-color: var(--primary-color);
        }
    </style>
</head>
<body>
<nav class="navbar">
    <div class="navbar-content">
        <a href="#" class="logo">EmailCraft</a>
    </div>
</nav>

<main class="main-content">
    <div class="editor-container">
        <div id="editor"></div>
        <div class="button-container">
            <div class="type-selector">
                <label for="email-category">邮件分类：</label>
                <select id="email-category">
                    <option value="marketing">营销类</option>
                    <option value="notification">通知类</option>
                    <option value="customer">客户关系类</option>
                    <option value="account">账户类</option>
                    <option value="internal">内部类</option>
                </select>
                <label for="email-type">邮件类型：</label>
                <select id="email-type">
                    <!-- 默认加载营销类邮件类型 -->
                    <option value="1">营销邮件</option>
                    <option value="5">促销邮件</option>
                    <option value="6">活动邀请</option>
                </select>
            </div>
            <div class="export-options">
                <button id="save-button" class="button button-secondary">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 7H5a2 2 0 00-2 2v9a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-3m-1 4l-3 3m0 0l-3-3m3 3V4" />
                    </svg>
                    保存设计
                </button>
                <button id="export-button" class="button button-secondary">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 16v1a3 3 0 003 3h10a3 3 0 003-3v-1m-4-8l-4-4m0 0L8 8m4-4v12" />
                    </svg>
                    导出
                </button>
                <!-- 新增发送按钮使用新ID -->
                <button id="send-button" class="button button-primary">
                    <svg xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"/>
                    </svg>
                    自动发送
                </button>
            </div>

        </div>
    </div>
</main>

<!-- 发送邮件模态框 -->
<div id="send-modal">
    <div class="send-modal-content">
        <span class="close">&times;</span>
        <h2>发送邮件设置</h2>
        <form id="send-form">
            <div class="form-group">
                <label>发件人邮箱</label>
                <input type="email" id="send-from" required placeholder="your-email@qq.com">
            </div>
            <div class="form-group">
                <label>SMTP授权码</label>
                <input type="password" id="send-password" required placeholder="16位授权码">
            </div>
            <div class="form-group">
                <label>收件人邮箱</label>
                <input type="email" id="send-to" required placeholder="recipient@example.com">
            </div>
            <div class="form-group">
                <label>邮件主题</label>
                <input type="text" id="send-subject" required placeholder="请输入邮件主题">
            </div>
            <div class="form-group">
                <label>添加附件</label>
                <div class="file-upload">
                    <!-- 隐藏原生input -->
                    <input type="file" id="attachment" multiple
                           accept=".pdf,.doc,.docx,.xls,.xlsx,.jpg,.png,.zip">
                    <!-- 自定义按钮 -->
                    <div class="custom-file-input">
                        <svg viewBox="0 0 24 24" width="24" height="24">
                            <path fill="currentColor" d="M14,2H6C4.9,2,4,2.9,4,4v16c0,1.1,0.9,2,2,2h12c1.1,0,2-0.9,2-2V8L14,2z M13,9V3.5L18.5,9H13z M16,19h-3v2h-2v-2H8v-2h3v-2h2v2h3V19z"/>
                        </svg>
                        <span>点击选择文件</span>
                    </div>
                    <!-- 文件信息展示 -->
                    <div class="file-info">未选择任何文件</div>
                </div>
                <small class="hint">支持多选文件(按住Ctrl/Command键选择多个文件)，单个不超过10MB</small>
            </div>
            <div class="form-buttons">
                <button type="submit" class="button button-primary">立即发送</button>
                <button type="button" id="cancel-send" class="button button-secondary">取消</button>
            </div>
        </form>
    </div>
</div>

<!-- 预览模态框 -->
<div id="preview-modal">
    <div class="modal-content">
        <span class="close">&times;</span>
        <div id="preview-content"></div>
    </div>
</div>

<!-- 标题输入模态框 -->
<div id="title-modal">
    <div class="title-modal-content">
        <h2>请输入邮件标题</h2>
        <input type="text" id="title-input" placeholder="邮件标题" />
        <div>
            <button id="confirm-save-button" class="button button-primary">确认保存</button>
            <button id="cancel-save-button" class="button button-secondary">取消</button>
        </div>
    </div>
</div>



<!-- 提示信息 -->
<div id="toast" class="toast"></div>

<script src="https://editor.unlayer.com/embed.js"></script>
<script>
    // 🌟 动态加载自定义汉化文件
    fetch('/zh-CN.json')
        .then(response => response.json())
        .then(customTranslations => {
            unlayer.init({
                id: 'editor',
                projectId: 1,
                locale: 'zh-CN',
                translations: {
                    'zh-CN': customTranslations, // 注入自定义翻译
                },
                appearance: {
                    theme: 'light',
                    panels: {
                        tools: { dock: 'left' }
                    }
                }
            });
        });

    // 邮件类型分类数据
    const emailTypes = {
        marketing: [
            { value: '1', label: '营销邮件' },
            { value: '5', label: '促销邮件' },
            { value: '6', label: '活动邀请' }
        ],
        notification: [
            { value: '2', label: '通知邮件' },
            { value: '9', label: '订单确认' },
            { value: '10', label: '发货通知' }
        ],
        customer: [
            { value: '4', label: '欢迎邮件' },
            { value: '7', label: '节日问候' },
            { value: '8', label: '客户反馈' },
            { value: '9', label: '面试邮件' }
        ],
        account: [
            { value: '11', label: '账户更新' },
            { value: '12', label: '密码重置' },
            { value: '13', label: '订阅确认' }
        ],
        internal: [
            { value: '15', label: '内部通知' },
            { value: '16', label: '招聘信息' },
            { value: '17', label: '合作伙伴通知' }
        ]
    };

    // 检查用户登录状态
    async function checkLoginStatus() {
        try {
            const response = await fetch('/api/v1/users/isLogin', {
                method: 'GET',
                headers: {
                    'Content-Type': 'application/json'
                }
            });
            const data = await response.json();
            if (data.code === 200 && data.data.login) {
                console.log('用户已登录，用户名：', data.data.username);
            } else {
                // 未登录，跳转到登录页面
                window.location.href = '/login.html'; // 替换为你的登录页面路径
            }
        } catch (error) {
            console.error('检查登录状态失败：', error);
            showToast('检查登录状态失败，请稍后重试');
        }
    }

    // 页面加载时检查登录状态
    window.addEventListener('load', function () {
        checkLoginStatus();
    });

    // 邮件分类选择事件
    const emailCategory = document.getElementById('email-category');
    const emailType = document.getElementById('email-type');

    emailCategory.addEventListener('change', function() {
        const selectedCategory = emailCategory.value;
        const types = emailTypes[selectedCategory];
        emailType.innerHTML = types.map(type =>
            `<option value="${type.value}">${type.label}</option>`
        ).join('');
    });

    // 保存按钮点击事件
    document.getElementById('save-button').addEventListener('click', function() {
        // 显示标题输入模态框
        const titleModal = document.getElementById('title-modal');
        titleModal.style.display = 'block';
    });

    // 确认保存按钮点击事件
    document.getElementById('confirm-save-button').addEventListener('click', async function () {
        const titleInput = document.getElementById('title-input').value;
        if (!titleInput) {
            showToast('请输入邮件标题');
            return;
        }

        const emailTypeValue = emailType.value;
        unlayer.exportHtml(async function (data) {
            console.log('导出的 HTML 内容：', data.html);
            if (data.html) {
                const saveResponse = await fetch('/api/v1/userTemplates/save', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({
                        title: titleInput,
                        content: data.html,
                        categoryId: emailTypeValue
                    })
                });
                const saveData = await saveResponse.json();
                if (saveData.code === 200) {
                    showToast('邮件已成功保存！');
                    // 保存成功后关闭模态框
                    document.getElementById('title-modal').style.display = 'none';
                } else {
                    showToast('保存模板失败：' + saveData.message);
                }
            } else {
                console.error('HTML 内容为空，请检查模板内容');
            }
        });
    });

    // 取消保存按钮点击事件
    document.getElementById('cancel-save-button').addEventListener('click', function() {
        document.getElementById('title-modal').style.display = 'none';
    });

    // 导出按钮点击事件
    document.getElementById('export-button').addEventListener('click', async function () {
        // 检查导出权限
        const checkPermissionResponse = await fetch('/api/v1/userTemplates/check-export-permission', {
            method: 'POST',
            headers: {
                'Content-Type': 'application/json'
            }
        });

        const permissionData = await checkPermissionResponse.json();
        if (permissionData.code === 200 && permissionData.data.isExport) {
            // 有权限导出，获取模板的 HTML 代码
            unlayer.exportHtml(function (data) {
                const htmlContent = data.html;

                // 安全降级方案
                const textArea = document.createElement('textarea');
                textArea.value = htmlContent;
                textArea.style.position = 'fixed';
                textArea.style.left = '-9999px';  // 隐藏元素
                document.body.appendChild(textArea);
                textArea.select();

                try {
                    const successful = document.execCommand('copy');
                    if (successful) {
                        showToast('已复制到剪贴板');
                    } else {
                        throw new Error('浏览器不支持自动复制');
                    }
                } catch (err) {
                    console.error('复制失败:', err);
                    // 显示预览模态框让用户手动复制
                    document.getElementById('preview-content').innerHTML = htmlContent;
                    document.getElementById('preview-modal').style.display = 'block';
                    showToast('请手动选择内容复制');
                } finally {
                    document.body.removeChild(textArea);
                }
            });
        } else {
            showToast('无权限导出模板');
        }
    });

    // 关闭预览模态框
    document.querySelector('.close').addEventListener('click', function() {
        document.getElementById('preview-modal').style.display = 'none';
    });

    // 点击模态框外部关闭
    window.addEventListener('click', function(event) {
        const previewModal = document.getElementById('preview-modal');
        const titleModal = document.getElementById('title-modal');
        if (event.target === previewModal) {
            previewModal.style.display = 'none';
        }
        if (event.target === titleModal) {
            titleModal.style.display = 'none';
        }
    });

    function showToast(message) {
        const toast = document.getElementById('toast');
        if (toast) {
            toast.textContent = message;
            toast.style.display = 'block';
            toast.style.animation = 'fadeInOut 3s ease-out'; // 应用动画
            setTimeout(() => {
                toast.style.display = 'none';
            }, 3000); // 3秒后隐藏
        } else {
            console.error('未找到 toast 元素');
        }
    }

    // ======== 发送邮件功能 ========
    document.getElementById('send-button').addEventListener('click', async function() {
        try {
            // 1. 发送权限检查请求
            const response = await fetch('/api/v1/userTemplates/check-export-permission', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({}) // 根据接口要求传递必要参数
            });

            // 2. 检查HTTP状态码
            if (!response.ok) {
                throw new Error(`权限检查失败 (HTTP ${response.status})`);
            }

            // 3. 解析JSON数据
            const data = await response.json();

            // 4. 根据业务逻辑判断权限
            if (data.code === 200 && data.data?.isExport) {
                document.getElementById('send-modal').style.display = 'block';
            } else {
                showToast(data.message || '🚫 无发送权限');
            }
        } catch (error) {
            console.error('权限检查异常:', error);
            showToast('❌ 权限验证失败: ' + error.message);
        }
    });

    // ================== 修正后的文件上传逻辑 ==================
    // 限定作用域到发送弹窗内部
    const sendModal = document.getElementById('send-modal');
    const fileInput = sendModal.querySelector('#attachment');
    const fileInfo = sendModal.querySelector('.file-info');
    const uploadContainer = sendModal.querySelector('.file-upload');

    // 显示选中文件信息（增强多文件显示）
    fileInput.addEventListener('change', function() {
        const files = Array.from(this.files);
        const fileList = files.map((file, index) =>
            `${index + 1}. ${file.name} (${(file.size/1024/1024).toFixed(2)}MB)`
        ).join('\n');

        fileInfo.textContent = files.length > 0
            ? `已选择 ${files.length} 个文件：\n${fileList}`
            : '未选择任何文件';
    });

    // 优化拖拽处理（兼容所有浏览器）
    uploadContainer.addEventListener('drop', function(e) {
        e.preventDefault();
        this.classList.remove('dragover');

        // 创建新的文件列表
        const dataTransfer = new DataTransfer();

        // 逐个添加文件（解决部分浏览器限制）
        Array.from(e.dataTransfer.files).forEach(file => {
            if (file.size > 10 * 1024 * 1024) {
                showToast(`文件 ${file.name} 超过10MB限制`);
                return;
            }
            dataTransfer.items.add(file);
        });

        // 更新文件输入（兼容旧浏览器写法）
        fileInput.files = dataTransfer.files;

        // 创建完整的事件对象（必须包含bubbles属性）
        const changeEvent = new Event('change', {
            bubbles: true,
            cancelable: true
        });
        fileInput.dispatchEvent(changeEvent);
    });

    // 增加手动选择的二次确认
    uploadContainer.querySelector('.custom-file-input').addEventListener('click', function() {
        // 清空旧选择避免覆盖
        fileInput.value = '';
    });


    // 发送表单提交事件（完整修改版）
    document.getElementById('send-form').addEventListener('submit', async function(e) {
        e.preventDefault();

        // 获取表单数据
        const fromEmail = document.getElementById('send-from').value;
        const password = document.getElementById('send-password').value;
        const toEmail = document.getElementById('send-to').value;
        const subject = document.getElementById('send-subject').value;
        const files = document.getElementById('attachment').files;

        // 校验必填字段
        if (!fromEmail || !password || !toEmail || !subject) {
            showToast('❌ 请填写所有必填项');
            return;
        }

        // 获取邮件内容
        unlayer.exportHtml(async (data) => {
            if (!data.html) {
                showToast('❌ 邮件内容不能为空');
                return;
            }

            try {
                // 创建FormData对象（支持文件上传）
                const formData = new FormData();
                formData.append('fromEmail', fromEmail);
                formData.append('smtpPassword', password);
                formData.append('toEmail', toEmail);
                formData.append('subject', subject);
                formData.append('htmlContent', data.html);

                // 添加多个附件（字段名需与后端@RequestParam一致）
                for (let i = 0; i < files.length; i++) {
                    formData.append('attachments', files[i]);
                }

                // 显示加载状态
                const sendBtn = document.querySelector('#send-form [type="submit"]');
                sendBtn.disabled = true;
                sendBtn.innerHTML = '<div class="spinner"></div> 发送中...';

                // 发送请求
                const response = await fetch('/api/v1/emails/send', {
                    method: 'POST',
                    body: formData // 不要设置Content-Type，浏览器会自动处理
                });

                // 处理响应
                const result = await response.json();
                if (response.ok) {
                    showToast('✅ 邮件发送成功');
                    document.getElementById('send-modal').style.display = 'none';
                } else {
                    showToast(`❌ 发送失败: ${result.message || '未知错误'}`);
                }
            } catch (error) {
                showToast('🌐 网络异常，请检查连接');
            } finally {
                // 重置按钮状态
                const sendBtn = document.querySelector('#send-form [type="submit"]');
                sendBtn.disabled = false;
                sendBtn.textContent = '立即发送';
            }
        });
    });

    // 关闭发送弹窗
    document.querySelectorAll('#send-modal .close, #cancel-send').forEach(btn => {
        btn.addEventListener('click', () => {
            document.getElementById('send-modal').style.display = 'none';
        });
    });
</script>
</body>
</html>